<template>
  <vxe-table
    border
    ref="xTable"
    show-overflow
    row-id="taskCode"
    :data="tableData"
    :loading="loading"
    resizable
    class="sortable-tree-demo"
    @menu-click="contextMenuClickEvent"
    :tree-config="{children: 'children',expandAll:true}">
    <!-- :menu-config="{body: {options: bodyMenus}}" -->
    <!-- <vxe-table-column width="60">
      <template v-slot>
        <span class="drag-btn">
          <i class="vxe-icon--menu"></i>
        </span>
      </template>
      <template v-slot:header>
        <vxe-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
          <i class="vxe-icon--question" @click="showHelpTip1 = !showHelpTip1"></i>
        </vxe-tooltip>
      </template>
    </vxe-table-column> -->
    <vxe-table-column type="seq"  width="100" title="序号" tree-node></vxe-table-column>
    <!-- <vxe-table-column type="serialNumber" width="120" title="序号" fixed="left" tree-node></vxe-table-column> -->
    <vxe-table-column field="taskName" width="180" title="任务名称" ></vxe-table-column>
    <vxe-table-column field="taskCode" width="80" title="任务编码" ></vxe-table-column>
    <vxe-table-column field="constructionPeriod" width="80" title="工期">
      <template v-slot="{ row }">
        <span>{{diff(row)}}</span>
      </template>
    </vxe-table-column>
    <vxe-table-column field="startTime" width="120" title="开始"></vxe-table-column>
    <vxe-table-column field="endTime" width="120" title="结束"></vxe-table-column>
    <vxe-table-column field="timeout" width="80" title="过期">
      <template v-slot="{ row }">
        <span>{{timeout(row)}}</span>
      </template>
    </vxe-table-column>
    <vxe-table-column field="actualEndTime" width="80" title="实际完成"></vxe-table-column>
    <vxe-table-column field="taskLevel" width="80" title="任务分级">
      <template v-slot="{ row }">
        <a-tag v-if="row.taskLevel === '0'">普通</a-tag>
        <a-tag v-else-if="row.taskLevel === '1'" color="blue">重要</a-tag>
        <a-tag v-else-if="row.taskLevel === '2'" color="orange">紧急</a-tag>
        <a-tag v-else-if="row.taskLevel === '3'" color="red">重要紧急</a-tag>
      </template>
    </vxe-table-column>
    <vxe-table-column field="taskProgress" width="100" title="完成比">
      <template v-slot="{ row }">
        <a-progress :showInfo="true" :percent="row.taskProgress" />
      </template>
    </vxe-table-column>
    <vxe-table-column field="taskStatus" width="80" title="状态">
      <template v-slot="{ row }">
        <span>{{getFilterDictTextByCache(row.taskStatus)}}</span>
      </template>
    </vxe-table-column>
    <vxe-table-column field="taskDirector_dictText" width="80" title="负责人"></vxe-table-column>
    <vxe-table-column field="taskReviewer_dictText" width="80" title="审核人"></vxe-table-column>
    <vxe-table-column field="preTask" width="80" title=前置任务></vxe-table-column>
    <vxe-table-column field="planManHours" width="80" title="预计工时"></vxe-table-column>
    <vxe-table-column field="actualManHours" width="80" title="实际工时"></vxe-table-column>
    <vxe-table-column field="remarks" width="80" title="备注"></vxe-table-column>
    <vxe-table-column title="操作" width="120" fixed="right">
      <template v-slot="{ row }">
        <a @click="editEvent(row)" v-if="hasPower && row.taskStatus !== '3'">编辑</a>
        <a-divider v-if="hasPower && row.taskStatus !== '3'" type="vertical"/>
        <a-dropdown>
          <a class="ant-dropdown-link">更多<a-icon type="down"/></a>
          <a-menu slot="overlay">
            <a-menu-item v-if="hasPower && row.taskStatus !== '3'">
              <a @click="addChildEvent(row)">添加子任务</a>
            </a-menu-item>
            <a-menu-item>
              <a @click="handleDetail(row)">详情</a>
            </a-menu-item>
            <a-menu-item v-if="hasPower && row.taskStatus === '0' && row.hasChildren !== '1'">
              <a @click="startEvent(row)">开始</a>
            </a-menu-item>
            <a-menu-item v-if="hasPower && row.taskStatus === '2' && row.hasChildren !== '1'">
              <a @click="checkEvent(row)" >审核</a>
            </a-menu-item>
            <a-menu-item v-if="hasPower && row.taskStatus === '3' && row.hasChildren !== '1'">
              <a @click="resetEvent(row)" >重启任务</a>
            </a-menu-item>
            <a-menu-item v-if="hasPower && row.taskStatus === '1'">
              <a @click="handleTaskTime(row)">填写工时</a>
            </a-menu-item>
            <a-menu-item v-if="hasPower">
              <a-popconfirm title="确定删除吗?" @confirm="() => removeEvent(row)">
                <a>删除</a>
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </template>
    </vxe-table-column>
  </vxe-table>
</template>

<script>
import moment from 'moment'
import Sortable from 'sortablejs/modular/sortable.core.esm.js'
import XEUtils from 'xe-utils'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import { getAction, deleteAction, putAction } from '@/api/manage'
// import { mapGetters } from 'vuex'
export default {
  name: 'TaskTree',
  props: ['projectCode', 'hasPower'],
  data() {
    return {
      tableData: [],
      url: {
        list: '/pms/task/treeList',
        delete: '/pms/task/delete',
        add: '/pms/task/add',
        edit: '/pms/task/edit',
        queryByCode: '/pms/task/queryByCode'
      },
      bodyMenus: [
        [
          { code: 'reduce', name: '向上合并', disabled: false }
          // { code: 'upgrade', name: '升级', disabled: false }
        ]
      ],
      loading: false,
      showHelpTip1: false,
      treeConfig: {
        children: 'children'
      }
    }
  },
  watch: {
    projectCode(val) {
      this.loadData()
    }
  },
  created() {
    this.treeDrop()
  },
  beforeDestroy() {
    if (this.sortable2) {
      this.sortable2.destroy()
    }
  },
  methods: {
    contextMenuClickEvent({ menu, row, column }) {
      const xTree = this.$refs.xTree
      switch (menu.code) {
        case 'reduce':
          this.reduce(row)
          break
        case 'upgrade':
          xTree.resetColumn()
          break
      }
    },
    reduce(selfRow) {
      const xTable = this.$refs.xTable
      const options = { children: 'children' }
      const index = xTable.getVTRowIndex(selfRow)
      const tableTreeData = this.tableData
      const selfNode = XEUtils.findTree(tableTreeData, row => row === selfRow, options)
      let prevRow, currRow
      if (index > 0) {
        prevRow = xTable.getData(index - 1)
        currRow = selfNode.items.splice(selfNode.index, 1)[0]
      } else { // 处理子节点获取不到index
        const parent = xTable.getRowById(selfRow.parentTaskCode)
        let index_
        parent.children.forEach((item, i) => {
          if (item.id === selfRow.id) {
            index_ = i
            return false
          }
        })
        prevRow = parent.children[index_ - 1]
        currRow = selfNode.items.splice(index_, 1)[0]
      }
      const flag = this.checkPreTask(currRow, prevRow)
      if (!flag) {
        this.$confirm({
          title: '当前任务的父任务不能作为前置任务',
          content: '点击是会清空该的前置任务',
          onOk() {
            this.reduceTask(prevRow['children'], 0, 0, currRow, prevRow)
          },
          onCancel() {
            console.log('Cancel')
          }
        })
      } else {
        // currRow.parentTaskCode = prevRow.parentTaskCode
        // if (prevRow['children'] && prevRow['children'].length > 0) {
        //   prevRow['children'].splice(0, 0, currRow)
        // } else {
        //   prevRow['children'] = [currRow]
        // }
        this.reduceTask(prevRow['children'], 0, 0, currRow, prevRow)
      }
      xTable.syncData()
      this.setIndex(this.tableData)
    },
    setIndex(list, index) { // 设置tree数据序号
      list.forEach((item, i) => {
        if (index) {
          item.index = index + '-' + (i + 1)
        } else {
          item.index = i + 1
        }
        if (item.children && item.children.length > 0) {
          this.setIndex(item.children, item.index)
        }
      })
    },
    treeDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable
        this.sortable2 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          invertSwap: true,
          handle: '.drag-btn',
          onEnd: ({ item, oldIndex }) => {
            const options = { children: 'children' }
            const targetTrElem = item
            const wrapperElem = targetTrElem.parentNode
            const prevTrElem = targetTrElem.previousElementSibling
            const tableTreeData = this.tableData
            const selfRow = xTable.getRowNode(targetTrElem).item
            const selfNode = XEUtils.findTree(tableTreeData, row => row === selfRow, options)
            if (prevTrElem) {
              // 移动到节点
              const prevRow = xTable.getRowNode(prevTrElem).item
              const prevNode = XEUtils.findTree(tableTreeData, row => row === prevRow, options)
              if (XEUtils.findTree(selfRow[options.children], row => prevRow === row, options)) {
                // 错误的移动
                const oldTrElem = wrapperElem.children[oldIndex]
                wrapperElem.insertBefore(targetTrElem, oldTrElem)
                return this.$XModal.message({ message: '不允许自己给自己拖动！', status: 'error' })
              }
              const currRow = selfNode.items.splice(selfNode.index, 1)[0]
              if (xTable.isTreeExpandByRow(prevRow)) {
                // 移动到当前的子节点
                currRow.parentTaskCode = prevRow.taskCode
                prevRow[options.children].splice(0, 0, currRow)
              } else {
                // 移动到相邻节点
                currRow.parentTaskCode = prevRow.parentTaskCode
                prevNode.items.splice(prevNode.index + (selfNode.index < prevNode.index ? 0 : 1), 0, currRow)
              }
            } else {
              // 移动到第一行
              const currRow = selfNode.items.splice(selfNode.index, 1)[0]
              currRow.parentTaskCode = '0'
              tableTreeData.unshift(currRow)
            }
            // 如果变动了树层级，需要刷新数据
            xTable.syncData()
            this.setIndex(this.tableData)
          }
        })
      })
    },
    reduceTask(items, startIndex, endIndex, currRow, prevRow) {
      currRow.parentTaskCode = prevRow.parentTaskCode
      if (items && items.length > 0) {
        items.splice(0, 0, currRow)
      } else {
        items = [currRow]
      }
    },
    checkPreTask(currRow, prevRow) { // 改变顺序时校验前置任务是否合法
      if (currRow.preTaskCode === prevRow.taskCode) {
        return false
      } else if (currRow.children && currRow.children.length > 0) {
        let flag = true
        currRow.children.forEach(item => {
          if (!this.checkPreTask(item, prevRow)) {
            flag = false
            return false
          }
        })
        return flag
      }
      return true
    },
    editEvent(data) {
      this.$emit('fn', 'edit', data)
    },
    addChildEvent(data) {
      this.$emit('fn', 'addChild', data)
    },
    handleTaskTime(data) {
      this.$emit('fn', 'taskTime', data)
    },
    handleDetail(data) {
      this.$emit('fn', 'detail', data)
    },
    checkEvent(data) {
      this.$emit('fn', 'check', data)
    },
    startEvent(data) {
      this.$emit('fn', 'start', data)
    },
    resetEvent(data) {
      const newData = { ...data }
      newData.taskStatus = '0'
      newData.taskProgress = 0
      putAction(this.url.edit, newData).then(res => {
        if (res.success) {
          this.$message.success('重启成功')
          data.taskStatus = '0'
          data.taskProgress = 0
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    removeEvent(row) {
      deleteAction(this.url.delete, { code: row.taskCode }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    loadData() {
      this.loading = true
      getAction(this.url.list, { projectCode: this.projectCode }).then(res => {
        if (res.success) {
          this.tableData = res.result
        } else {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    // loadProjectData() {
    //   getAction('pms/project/list', { projectCode: this.projectCode }).then(res => {
    //     if (res.success) {
    //       this.projectData = res.result
    //     } else {
    //       this.$message.warning(res.message)
    //     }
    //   })
    // },
    getFilterDictTextByCache(val) {
      return filterDictTextByCache('pms_task_status', val)
    },
    hasChild(row) {
      if (row.hasChildren === '1') {
        return true
      } else {
        return false
      }
    },
    diff(row) {
      if (row.endTime === row.startTime) {
        return 1
      } else {
        const endTime = moment(row.endTime)
        const startTime = moment(row.startTime)
        return endTime.diff(startTime, 'day')
      }
    },
    timeout(row) {
      if (row.taskStatus !== '3') {
        const endTime = moment(row.endTime)
        const startTime = moment(new Date())
        const timeout = startTime.diff(endTime, 'day')
        return timeout > 0 ? timeout : ''
      } else {
        return ''
      }
    }
  },
  mounted() {
    this.loadData()
    // this.loadProjectData()
  }
}
</script>
<style>
  .sortable-tree-demo .drag-btn {
    cursor: move;
    font-size: 12px;
  }
  .sortable-tree-demo .vxe-body--row.sortable-ghost,
  .sortable-tree-demo .vxe-body--row.sortable-chosen {
    background-color:#dfecfb;
  }
</style>

<style scoped>
  @import '~@assets/less/common.less';

</style>
